<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :auto-upload="false"
      :file-list="list"
      :limit="limit"
      :class="{ hidden: limit === list.length }"
      :on-change="handleChange"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-show="percent > 0" style="width:400px" :percentage="percent" />
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
// SECRETID 和 SECRETKEY 请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDzpTs9C1bx62kDD4nMlxwkOp48ygBSU3S',
  SecretKey: 'FHE7yiLm01qUu78wWs071g8OZWFtMbbL'
})
export default {
  props: {
    limit: {
      type: Number,
      //   默认一条数据
      default: 1
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      list: [],
      percent: 0
    }
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList)
      const index = this.list.findIndex((item) => item.uid === file.uid)
      this.list.splice(index, 1)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    async handleChange(file, fileList) {
      const res = await cos.uploadFile({
        Bucket: 'super-1316543954' /* 填写自己的 bucket，必须字段 */,
        Region: 'ap-shanghai' /* 存储桶所在地域，必须字段 */,
        Key:
          Date.now() +
          file.raw
            .name /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
        Body: file.raw, // 上传文件对象
        SliceSize:
          1024 *
          1024 *
          5 /* 触发分块上传的阈值，超过5MB 使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */,
        onProgress: (data) => {
          console.log(data)
          this.percent = Math.ceil(data.percent * 100)
        }
      })
      console.log(res)
      this.list.push({
        name: res.Location,
        url: 'https://' + res.Location
      })
      setTimeout(() => {
        this.percent = 0
      }, 1000)
    }
  }
}
</script>

<style scoped lang='scss'>
::v-deep .hidden .el-upload--picture-card {
  display: none;
}

::v-deep .el-upload-list__item.is-ready {
  display: none;
}
</style>
